package com.zhouzi.zhaoyang.adapter.rvadapter.common;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author Jasmine
 *   Created on 2019/6/10
 *   explain: recycle adapter 基类
 *   SuppressWarnings / SuppressLint注解？？
 */
@SuppressWarnings("unused")
@SuppressLint("RecyclerView")
public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> {

    private String TAG = this.getClass().getCanonicalName();

    /** 适配器： 布局， 数据， Context, 监听事件 */
    protected abstract int getLayoutId();
    protected abstract List<T> getData();
    protected abstract Context getContext();
    /** 监听事件 */
    private OnItemClickListener clickEvent;
    public void setViewClick(OnItemClickListener action){
        this.clickEvent=action;
    }
    /** 重写方法体
     * @param holder 复用的viewHolder
     * @param item   当前子项
     * @param position  所处集合位置
     * */
    protected abstract void convert(BaseViewHolder holder, T item, int position);

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(getContext()).inflate(getLayoutId(),parent ,false);
        return new BaseViewHolder(view,null);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, final int position) {
        //绑定BaseViewHolder的数据显示，监听等
        convert(holder,getItem(position),position);

        if(clickEvent!=null){
            final View finalConvertView = holder.getConvertView();
            finalConvertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickEvent.onItemClick(v,getItem(position),position);
                }
            });
            finalConvertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    clickEvent.onItemLongClick(v,getItem(position),position);
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
//        TODO 三元运算符  待修改6
        return (getData()!=null)?getData().size():4;
    }
    private T getItem(int position){
        return (getData()==null) ?null:getData().get(position);
    }
    /** 插入一条数据 */
    public void addData(int position,T item){
        getData().add(position,item);
        notifyItemInserted(position);
    }
    /** 删除一条数据 */
    public void deleteData(int position){
        getData().remove(position);
        notifyItemRemoved(position);
    }
}
